//
//  HDForgetPWViewController.swift
//  HuaDaoPeifu
//
//  Created by liangyuanliangyuan on 16/4/20.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD

class HDForgetPWViewController: UIViewController ,UITextFieldDelegate{

    let phone = HDIconTextFieldView()
    let authCode = HDIconTextFieldView()
    var progressAlert = HDProgressAlert()
    var nextButton = HDNextStepButton(title: "下一步")
    var repwdStr = PYPRepwd()
    var passWordVC = HDPasswordViewController(setType: PwdType.reset)
    //倒计时
    var countdownTimer: Timer?
    var remainingSeconds: Int = 0 {
        willSet {
            authCode.getCodeButton.setTitle("(\(newValue)秒)", for: UIControlState())
            if newValue <= 0 {
                authCode.getCodeButton.setTitle("重新获取", for: UIControlState())
                isCounting = false
            }
        }
    }
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
                remainingSeconds = 60
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
            }
            authCode.getCodeButton.isEnabled = !newValue
        }
    }
    func updateTime(_ timer: Timer) {
        remainingSeconds -= 1
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "忘记密码"
        view.backgroundColor = UIColor(hex: 0xf8f8f8)
        setupViews()
        phone.textField.delegate = self
        authCode.textField.delegate = self
//        authCode.delegate = self
        
    }


    func nextButtonAction(){
        
        if phone.textField.text == nil || phone.textField.text == "" {
            progressAlert.pleaseEnterPhoneNumber()
            return
        }
        if authCode.textField.text == nil || authCode.textField.text == "" {
            progressAlert.pleaseEnterAuthCode()
            return
        }

        codeVerti()
        
        let phoneNumber = phone.textField.text
        let codeNumber = authCode.textField.text
        
        let ckAuthCode = PYPCkauthcode(phone: phoneNumber, code: codeNumber, reqmode: "2")
        HDApiManagerHandler.requestCkauthcode(ckAuthCode, success: { [unowned self](dict) in
            if dict["status"]?.int32Value == 1{
            print(dict)
                self.passWordVC.regStr?.phone = ckAuthCode.phone
                self.passWordVC.regStr?.code = ckAuthCode.code
                let contr = HDPasswordViewController(setType:PwdType.reset)
                contr.repwdStr.phone = ckAuthCode.phone
                contr.repwdStr.code = ckAuthCode.code
            self.navigationController?.pushViewController(contr, animated: true)
            }else{
            let msg = dict["msg"] as! String
            SVProgressHUD.showError(msg)
            }
            }) { (error) in
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    func codeVerti(){
        let ckAuthCode = PYPCkauthcode(phone: phone.textField.text, code:authCode.textField.text, reqmode: "2")
        HDApiManagerHandler.requestCkauthcode(ckAuthCode, success: { (dict) in
            if dict["status"]?.int32Value == 1 {
                return
            }
            let msg = dict["msg"] as! String
            SVProgressHUD.showError(msg)
        }) { (error) in
        }
    }

    func getCodeButtonChange (_ sender: UITextField) {
        if phone.textField.text?.characters.isEmpty == true {
            authCode.getCodeButton.setTitleColor(UIColor(hex:0x999999), for: UIControlState())
        }else {
            authCode.getCodeButton.setTitleColor(ConstantColor.appThemeColor, for: UIControlState())
        }
    }
    
    func setupViews() {
        phone.icon.image = UIImage(named: "phone")
        phone.textField.placeholder = "请输入手机号"
        phone.textField.clearButtonMode = .whileEditing
        phone.textField.keyboardType = .numberPad
        phone.textField.addTarget(self, action: #selector(getCodeButtonChange(_:)), for: .editingChanged)
        self.view.addSubview(phone)
        phone.snp.makeConstraints { (make) in
            make.top.equalTo(45)
            make.left.equalTo(self.view).offset(-1)
            make.right.equalTo(self.view).offset(1)
            make.height.equalTo(49)
        }
        
        authCode.icon.image = UIImage(named: "验证码")
        authCode.textField.placeholder = "请输入验证码"
        authCode.textField.keyboardType = .numberPad
        authCode.getCodeButton.isHidden = false
        authCode.getCodeButton.addTarget(self, action: #selector(getCode), for: .touchUpInside)
        self.view.addSubview(authCode)
        authCode.snp.makeConstraints { (make) in
            make.top.equalTo(phone.snp.bottom).offset(10)
            make.left.equalTo(self.view).offset(-1)
            make.right.equalTo(self.view).offset(1)
            make.height.equalTo(49)
        }
        
        nextButton.addTarget(self, action: #selector(nextButtonAction), for: .touchUpInside)
        self.view .addSubview(nextButton)
        nextButton.snp.makeConstraints { (make) in
            make.left.equalTo(37)
            make.right.equalTo(-37)
            make.top.equalTo(authCode.snp.bottom).offset(50)
            make.height.equalTo(40)
        }
    }
    
    func getCode() {
        if phone.textField.text == nil || phone.textField.text == "" {
            progressAlert.pleaseEnterPhoneNumber()
            return
        }
        if phone.textField.text?.characters.count != 11 {
            progressAlert.pleaseEnterRightPhoneNumber()
            return
        }
        let phoneNumber = phone.textField.text
        let authCode = PYPAuthcode(phone:phoneNumber, tms: "0", reqmode: "2")
        
        HDApiManagerHandler.requestAuthcode(authCode, success: { [unowned self](dict) in
            if dict["status"]?.int32Value == 1 {
                #if DEBUG
                    let code = dict["data"] as! NSDictionary
                    print(code)
                    self.isCounting = true
                #endif
                return
            }
            let msg = dict["msg"] as! String
            SVProgressHUD.showError(msg)
            print(msg)
        }) { (error) in
            
        }
        
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
